<template>
  <div class="hello">
    <h1>学生信息管理</h1>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input
            v-model="searchForm.stuNo"
            placeholder="请输入学号"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.sex" placeholder="请选择性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select
            v-model="searchForm.classId"
            placeholder="请选择班级"
            @change="updateClassName"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地点">
          <el-input
            v-model="searchForm.location"
            placeholder="请输入地点"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="info" @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd" v-if="[0, 1].includes(role)">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      style="width: 100%"
      height="calc(100vh - 280px)"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column prop="id" label="ID" width="60"> </el-table-column>
      <el-table-column prop="name" label="姓名" min-width="100">
      </el-table-column>
      <el-table-column label="学号" prop="stuNo" min-width="100">
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="60">
        <template slot-scope="scope">
          {{ scope.row.sex === 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="tel" label="电话" min-width="120">
      </el-table-column>
      <el-table-column
        prop="className"
        label="班级"
        min-width="120"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="location"
        label="地点"
        min-width="120"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column label="操作" width="140" fixed="right" v-if="[0, 1].includes(role)">
        <template slot-scope="scope">
          <div class="operation-buttons">
            <el-button type="primary" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑学生信息对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form
        :model="form"
        :rules="rules"
        ref="studentForm"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="stuNo">
          <el-input v-model="form.stuNo" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="form.sex"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select
            v-model="form.classId"
            placeholder="请选择班级"
            style="width: 100%"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.className"
              :value="Number(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable no-unused-vars */
export default {
  name: "HelloWorld",
  data() {
    return {
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页参数
      pageSize: 10,
      pageNum: 1,
      total: 0,
      // 搜索表单
      searchForm: {
        name: "",
        sex: null,
        className: "",
        location: "",
        stuNo: "",
      },
      // 对话框相关
      dialogVisible: false,
      dialogTitle: "",
      dialogType: "", // 'add' 或 'edit'
      // 表单数据
      form: {
        id: "",
        name: "",
        sex: "",
        tel: "",
        classId: 0,
        stuNo: "",
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        stuNo: [
          { required: true, message: "请输入学号", trigger: "blur" },
          { validator: this.validateStuNoUnique, trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        tel: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        classId: [{ required: true, message: "请选择班级", trigger: "change" }],
      },
      // 班级列表
      classList: [],
    };
  },
  computed: {
    role() {
      console.log('role', this.getRole())
      return this.getRole();
    }
  },
  methods: {
    getRole() {
      const user = JSON.parse(localStorage.getItem('currentUser'));
      return user ? user.role : '';
    },
    // 学号唯一性校验
    validateStuNoUnique(rule, value, callback) {
      // 如果没有输入学号，不进行校验
      if (!value) {
        callback();
        return;
      }

      // 如果是编辑模式且学号没有改变，不进行校验
      if (this.dialogType === "edit" && this.originalStuNo === value) {
        callback();
        return;
      }

      // 调用后端接口检查学号是否存在
      this.$http
        .get("/student/checkStuNo", {
          params: { stuNo: value },
        })
        .then((res) => {
          if (res.data && res.data.code === 200) {
            // 如果学号不存在，校验通过
            if (!res.data.data) {
              callback();
            } else {
              // 如果学号已存在，校验失败
              callback(new Error("该学号已被使用，请更换"));
            }
          } else {
            // 接口调用失败
            callback(new Error("学号验证失败，请稍后再试"));
          }
        })
        .catch(() => {
          callback(new Error("网络请求失败，请检查网络连接"));
        });
    },
    // 处理查询
    handleSearch() {
      console.log(this.searchForm); // 检查 searchForm 的值
      this.pageNum = 1; // 重置到第一页
      this.loadData();
    },

    // 编辑操作
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogTitle = "编辑学生";
      this.openDialog(row);
    },

// 打开对话框通用方法
openDialog(row) {
  this.dialogVisible = true;
  // 加载班级列表
  this.loadClassList().then(() => {
    // 清空表单
    this.$nextTick(() => {
      if (this.$refs.studentForm) {
        this.$refs.studentForm.resetFields();
      }
      
      if (row) {
        // 编辑模式：填充表单数据
        this.originalStuNo = row.stuNo; // 记录原始学号
        
        this.form = {
          id: row.id,
          name: row.name,
          sex: row.sex,
          tel: row.tel,
          stuNo: row.stuNo, // 添加学号
          classId: Number(row.classId)
        };
      } else {
        // 新增模式：设置默认值
        this.originalStuNo = ''; // 清空原始学号
        this.form = {
          id: '',
          name: '',
          sex: 1,
          tel: '',
          stuNo: '', // 添加学号字段
          classId: ''
        };
      }
    });
  });
},

    // 提交表单
    submitForm() {
      this.$refs.studentForm.validate((valid) => {
        if (valid) {
          if (this.dialogType === "add") {
            this.confirmAdd();
          } else if (this.dialogType === "edit") {
            this.confirmEdit();
          }
        } else {
          return false;
        }
      });
    },

    // 加载数据
    loadData() {
      this.loading = true;
      this.$http.post("/student/listPage", {
          pageSize: this.pageSize,
          pageNum: this.pageNum,
          param: {
            name: this.searchForm.name,
            sex: this.searchForm.sex,
            className: this.searchForm.className,
            location: this.searchForm.location,
            stuNo: this.searchForm.stuNo,
          },
        })
        .then((res) => res.data)
        .then((res) => {
          this.loading = false;
          if (res.code == 200) {
            console.log("接口返回数据:", res);
            this.tableData = res.data;
            this.total = res.total;
          } else {
            this.$message.error("获取数据失败: " + res.msg);
          }
        })
        .catch((err) => {
          this.loading = false;
          console.error("请求错误:", err);
          this.$message.error("网络请求失败，请检查网络连接");
        });
    },
    // 重置查询条件
    resetSearch() {
      this.searchForm = {
        name: "",
        sex: null,
        tel: "",
        stuNo: "",
      };
      this.handleSearch();
    },
    // 处理每页条数变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.loadData();
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadData();
    },
    // 删除操作
    handleDelete(row) {
      this.$confirm("确认删除该学生信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete("/student/" + row.id)
            .then((res) => res.data)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("删除成功");
                this.loadData(); // 重新加载数据
              } else {
                this.$message.error("删除失败");
              }
            })
            .catch((err) => {
              console.error("删除请求错误:", err);
              this.$message.error("网络请求失败，请稍后重试");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 打开新增对话框
    handleAdd() {
      this.dialogType = "add";
      this.dialogTitle = "新增学生";
      this.openDialog();
    },
    // 加载班级列表
    loadClassList() {
      return this.$http
        .get("/class/list")
        .then((res) => {
          return res.data;
        })
        .then((res) => {
          if (res.code == 200) {
            this.classList = res.data || [];
          } else {
            console.error("获取班级列表失败:", res.msg);
          }
          return this.classList;
        })
        .catch((err) => {
          console.error("获取班级列表请求错误:", err);
          return [];
        });
    },
    // 确认新增
    confirmAdd() {
      this.form.sex = Number(this.form.sex);
      this.$http
        .post("/student/create", this.form)
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.loadData();
          } else {
            this.$message.error(res.msg || "添加失败");
          }
        })
        .catch((err) => {
          console.error("添加请求错误:", err);
          if (err.response && err.response.data) {
            this.$message.error(
              err.response.data.message || "网络请求失败，请稍后重试"
            );
          } else {
            this.$message.error("网络请求失败，请稍后重试");
          }
        });
    },
    // 确认编辑
    confirmEdit() {
      this.form.sex = Number(this.form.sex);
      this.$http
        .post("/student/update", this.form)
        .then((res) => res.data)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("更新成功");
            this.dialogVisible = false;
            this.loadData();
          } else {
            this.$message.error(res.msg || "更新失败");
          }
        })
        .catch((err) => {
          console.error("更新请求错误:", err);
          if (err.response && err.response.data) {
            this.$message.error(
              err.response.data.message || "网络请求失败，请稍后重试"
            );
          } else {
            this.$message.error("网络请求失败，请稍后重试");
          }
        });
    },
    // 更新班级名称
    updateClassName(value) {
      const selectedClass = this.classList.find((item) => item.id === value);
      this.searchForm.className = selectedClass ? selectedClass.className : "";
    },
  },
  created() {
    // 组件创建时加载数据
    this.loadData();
    // 加载班级列表
    this.loadClassList();
  },
};
</script>

<style scoped>
.hello {
  display: flex;
  flex-direction: column;
  height: 100%;
  margin: 0;
}

.search-container {
  margin-bottom: 15px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.el-table {
  flex: 1;
  overflow: hidden;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
  padding: 10px 0;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

.operation-buttons .el-button {
  margin-left: 0;
  margin-right: 5px;
  padding: 5px 8px;
}

/* 确保文本在单元格中不会被截断 */
::v-deep .el-table .cell {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
